package com.mxy.myapplication.service;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.mxy.myapplication.activity.MainActivity;

/**
 * 自定义ServiceConnection
 */
public class MyServiceConnection implements ServiceConnection {

  //通过Binder使Activity与Service相互持有
  private IMyBinder iMyBinder;
  private MainActivity mainActivity;
  //Activity与Service断开链接时最好制空避免内存溢出
  private MyService myService;

  public MyServiceConnection(MainActivity mainActivity) {
    this.mainActivity = mainActivity;
  }

  public IMyBinder getBinder() {
    return iMyBinder;
  }

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
    System.out.println("MyServiceConnection onServiceConnected");
    iMyBinder = (IMyBinder) service;
    iMyBinder.setActivity(mainActivity);
    iMyBinder.callmethodOfService1();
  }

  //Android 系统会在与服务的连接意外中断时（例如当服务崩溃或被终止时）调用该方法。注意:当客户端取消绑定时，系统“绝对不会”调用该方法。
  @Override
  public void onServiceDisconnected(ComponentName name) {
    myService = null;
    System.out.println("MyService  onServiceDisconnected");
  }
}